package com.imageim.yimirror.common.ui.analysis;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.analysisPhoto.AnalysisPhotoResultBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.ui.btn.BtnCircleClose;
import com.imageim.yimirror.common.util.CacheUtils;
import com.imageim.yimirror.common.util.PictureUtils;
import com.imageim.yimirror.common.util.SoundUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.service.statistic.StatisticSDK;
import com.imageim.yimirror.service.statistic.StatisticUtil;
import com.imageim.yimirror.ui.activity.MainActivity;
import com.imageim.yimirror.ui.activity.ScanFaceActivity;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

/**
 * Created by Bruce.Zhou on 2018/6/27 17:15.
 * Email: 907160968@qq.com
 */

public class AnalysisPhotoView extends RelativeLayout implements View.OnClickListener
        , GestureDetector.OnGestureListener {

    private GestureDetector gestureDetector;
    private float moveX;
    private AnalysisPhotoResultBean resultBean;
    private String pageId;

    public AnalysisPhotoView(Context context) {
        super(context);
        init();
    }

    public AnalysisPhotoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AnalysisPhotoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private ImageView ivPhoto;
    private ZhiNengView panelZhineng;
    private ClothAnalysisView panelClothAnalysis;
    private SuitableOccasionView panelSuitableOccasion;
    //    private SimilarToMeView panelSimilarToMe;
    private BtnCircleClose btnCircleClose;
    private GenderTipView genderTipView;
    private ImageView ivAvatar;
    private ImageView ivAvatarBg;
    //    private View panelAvatar;

    private void init() {
        View root = View.inflate(getContext(), R.layout.layout_analysis_photo_view, this);
        btnCircleClose = root.findViewById(R.id.btn_close);
        btnCircleClose.setOnTimeOverListener(new BtnCircleClose.OnTimeOverListener() {
            @Override
            public void onTimeOver() {
                ((Activity) getContext()).finish();
                StatisticSDK.endPage(pageId, 1);
            }
        });
        ivPhoto = root.findViewById(R.id.iv_photo);
        panelZhineng = root.findViewById(R.id.panel_zhineng);
        panelClothAnalysis = root.findViewById(R.id.panel_clothAnalysis);
        panelSuitableOccasion = root.findViewById(R.id.panel_suitable_occasion);
        //        panelSimilarToMe = root.findViewById(R.id.panel_similar);
        panelZhineng.setVisibility(View.INVISIBLE);
        panelClothAnalysis.setVisibility(View.INVISIBLE);
        panelSuitableOccasion.setVisibility(View.INVISIBLE);
        //        panelSimilarToMe.setVisibility(View.INVISIBLE);
        root.findViewById(R.id.btn_close).setOnClickListener(this);
        panelZhineng.setOnClickListener(this);
        panelClothAnalysis.setOnClickListener(this);
        panelSuitableOccasion.setOnClickListener(this);
        //        panelSimilarToMe.setOnClickListener(this);
        findViewById(R.id.btn_scroll_left).setOnClickListener(this);
        initTouchListener();
        genderTipView = root.findViewById(R.id.panel_gender_tip);
        findViewById(R.id.btn_reshot).setOnClickListener(this);
        findViewById(R.id.btn_next).setOnClickListener(this);
        ivAvatar = root.findViewById(R.id.iv_avatar);
        ivAvatarBg = root.findViewById(R.id.iv_avatar_bg);
        //        panelAvatar = findViewById(R.id.panel_avatar);
        findViewById(R.id.btn_next).setVisibility(View.INVISIBLE);
    }

    private void initTouchListener() {
        setClickable(true);
        setEnabled(true);
        gestureDetector = new GestureDetector(getContext(), this);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                gestureDetector.onTouchEvent(motionEvent);
                //                LogUtil.d("touch", "onTouch");
                return true;
            }
        });
    }

    public void startAnim() {
        startPanelAnim(panelZhineng, 1000);
        startPanelAnim(panelClothAnalysis, 1500);
        startPanelAnim(panelSuitableOccasion, 2000);
        //        startPanelAnim(panelSimilarToMe, 2600);
    }


    public void show() {
        setVisibility(View.VISIBLE);
        btnCircleClose.start(180);
        startAnim();
        pageId = StatisticUtil.getPageId(getClass().getName());
        StatisticSDK.startPage(pageId, 1);
    }

    public void setAvatar() {
        String faceStr = CacheUtils.getString(getContext(), Constants.FACE_STR);
        Bitmap avatar = BitmapUtils.base64ToBitmap(faceStr);
        Bitmap faceBitmap = PictureUtils.createCircleImage(avatar, avatar.getWidth());
        ivAvatar.setImageBitmap(faceBitmap);
        ivAvatarBg.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.rotate));
        findViewById(R.id.btn_next).setVisibility(View.VISIBLE);
        avatar.recycle();
    }

    /**
     * 放大它
     *
     * @param view
     * @param startDelay
     */
    private void startPanelAnim(final View view, long startDelay) {
        view.setScaleX(0);
        view.setScaleY(0);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 0, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 0, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0.2f, 1);
        scaleX.setInterpolator(new OvershootInterpolator(0.5f));
        scaleY.setInterpolator(new OvershootInterpolator(0.5f));
        scaleX.setDuration(1500);
        scaleY.setDuration(1500);
        alpha.setDuration(1500);
        AnimatorSet anim = new AnimatorSet();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                view.setVisibility(View.VISIBLE);
            }
        });
        anim.setTarget(view);
        anim.playTogether(scaleX, scaleY, alpha);
        anim.setStartDelay(startDelay);
        anim.start();
    }

    /**
     * 缩小它
     *
     * @param view
     */
    public static void scaleToDismiss(final View view) {
        if (view != null) {
            ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 0.4f);
            ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 0.4f);
            ObjectAnimator fadeout = ObjectAnimator.ofFloat(view, "alpha", 0.3f);
            AnimatorSet animSet = new AnimatorSet();
            animSet.setTarget(view);
            animSet.setDuration(1500);
            animSet.playTogether(scaleX, scaleY, fadeout);
            animSet.start();
        }
    }

    public void setPhoto(String photoPath) {
        GlideUtils.display(ivPhoto, photoPath);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_close:
                StatisticSDK.onEvent(6);
                ((Activity) getContext()).finish();
                break;
            case R.id.panel_zhineng: // 智能推荐
                if (isZhinengClickable()) {
                    StatisticSDK.onEvent(1);
                    Bundle data = new Bundle();
                    data.putInt(Constants.VIEW_CODE, EventCode.CODE_SET_FACE_ANALYSIS_VIEW);
                    SceneManager.toScene(getContext(), MainActivity.class, data);
                    ((Activity) getContext()).finish();
                }
                break;
            case R.id.panel_clothAnalysis: // 服装分析
                if (isClothClikable()) {
                    StatisticSDK.onEvent(2);
                    Bundle data = new Bundle();
                    data.putInt(Constants.VIEW_CODE, EventCode.CODE_SET_FACE_ANALYSIS_VIEW);
                    SceneManager.toScene(getContext(), MainActivity.class, data);
                    ((Activity) getContext()).finish();
                }
                break;
            case R.id.panel_suitable_occasion: // 适合场合
                if (isSuitableClickable()) {
                    StatisticSDK.onEvent(3);
                    Bundle data = new Bundle();
                    data.putInt(Constants.VIEW_CODE, EventCode.CODE_SET_SUITABLE_OCCASION_VIEW);
                    data.putString(Constants.OCCASIONIDS, panelSuitableOccasion.getOccasions());
                    SceneManager.toScene(getContext(), MainActivity.class, data);
                    ((Activity) getContext()).finish();
                }
                break;
            //            case R.id.panel_similar:
            //                Bundle data = new Bundle();
            //                data.putInt(Constants.VIEW_CODE, EventCode.CODE_SET_SIMILAR_VIEW);
            //                SceneManager.toScene(getContext(), MainActivity.class, data);
            //                ((Activity) getContext()).finish();
            //                break;
            case R.id.btn_scroll_left:
                if (resultBean != null && resultBean.getIfAll() == 2) {
                    SceneManager.toScene(getContext(), MainActivity.class, null);
                    ((Activity) getContext()).finish();
                }
                break;
            case R.id.btn_reshot:
                StatisticSDK.onEvent(4);
                SceneManager.toScene(getContext(), ScanFaceActivity.class, null);
                ((Activity) getContext()).finish();
                break;
            case R.id.btn_next:
                if (resultBean != null && resultBean.getIfAll() == 2) {
                    StatisticSDK.onEvent(5);
                    SceneManager.toScene(getContext(), MainActivity.class, null);
                    ((Activity) getContext()).finish();
                }
                break;
            default:
        }
        StatisticSDK.endPage(pageId, 1);
    }

    private boolean isZhinengClickable() {
        if (resultBean == null) {
            return false;
        }
        return !(TextUtils.isEmpty(resultBean.getFaceStyleName()) || TextUtils.isEmpty(resultBean.getClothingStyleName()));
    }

    private boolean isClothClikable() {
        if (resultBean == null) {
            return false;
        }
        return !TextUtils.isEmpty(resultBean.getLabels());
    }

    private boolean isSuitableClickable() {
        if (resultBean == null) {
            return false;
        }
        return !TextUtils.isEmpty(resultBean.getOccasionNames());
    }

    private boolean hasShowGenderTip = false;
    private boolean hasPlaySound = false;

    public void setData(AnalysisPhotoResultBean resultBean) {
        this.resultBean = resultBean;
        panelZhineng.setData(resultBean);
        panelClothAnalysis.setData(resultBean);
        panelSuitableOccasion.setData(resultBean);
        //        panelSimilarToMe.setData(resultBean);
        // 男女判断
        if (UserUtil.getShopMaleSupport() == 2) { // 1店铺支持男性，2店铺不支持男性
            if (resultBean.getGender() == 1 && !hasShowGenderTip) {
                hasShowGenderTip = true;
                if (genderTipView != null) {
                    genderTipView.setVisibility(View.VISIBLE);
                }
                genderTipView.startTimer();
                panelZhineng.setVisibility(View.INVISIBLE);
                panelClothAnalysis.setVisibility(View.INVISIBLE);
                panelSuitableOccasion.setVisibility(View.INVISIBLE);
                //            panelSimilarToMe.setVisibility(View.INVISIBLE);
            }
        }
        if (resultBean.getIfAll() == 2 && !hasPlaySound && resultBean.getGender() == 2) {
            hasPlaySound = true;
            SoundUtil.play(R.raw.a004);
        }
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        moveX = motionEvent.getX();
        return true;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    private boolean hasTrickerNextScene = false;

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        moveX += distanceX;
        if (moveX > 1000 && !hasTrickerNextScene) {
            if (resultBean != null && resultBean.getGender() == 2 && resultBean.getIfAll() == 2) {
                hasTrickerNextScene = true;
                SceneManager.toScene(getContext(), MainActivity.class, null);
                ((Activity) getContext()).finish();
                StatisticSDK.endPage(pageId, 1);
            }
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    public void destory() {
        panelZhineng.clearAnimation();
        panelClothAnalysis.clearAnimation();
        panelSuitableOccasion.clearAnimation();
        //        panelSimilarToMe.clearAnimation();
        ivAvatarBg.clearAnimation();
        removeAllViews();
        //        panelZhineng = null;
        //        panelClothAnalysis = null;
        //        panelSuitableOccasion = null;
        //        panelSimilarToMe = null;
        btnCircleClose.destory();
        btnCircleClose = null;
        genderTipView.destory();
        genderTipView = null;
    }

    public void restartTimer(int secends) {
        btnCircleClose.restart(secends);
    }
}